﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using ProjectDirector.Domain.Abstracts;
using ProjectDirector.ViewModels;
using System.ComponentModel;
using ProjectDirector.Domain.Entities;
using System.Web.Security;
using ProjectDirector.Domain.Concretes;
using System.Text;

namespace ProjectDirector.Controllers
{
    public class EmployeeController : Controller
    {
        private IProjectDirectorRepository repository = null;
        int PageSize = 20;
        public EmployeeController(IProjectDirectorRepository _repository) {
            this.repository = _repository;
        }
        //
        // GET: /Employee/

        [Authorize]
        public ActionResult List([DefaultValue(1)] int page)
        {
            var employees = repository.GetEmployees().Where(x => x.IsDeleted == null).OrderBy(x=>x.FirstName).ToList();
            var viewModel = new EmployeeViewModel
            {
                Employees = employees.Skip((page - 1) * PageSize).Take(PageSize).ToList(),
                PagingInfo = new Web.Models.PagingInfo
                {
                    CurrentPage = page,
                    ItemsPerPage = PageSize,
                    TotalItems = employees.Count()
                }
            };
            return View(viewModel);
        }

        //
        // GET: /Employee/Details/5
        [Authorize]
        public ActionResult Details(string id)
        {
            var employee = repository.GetEmployees().SingleOrDefault(x => x.UserId.ToString()== id);
            var viewModel = new EmployeeViewModel
            {
                Employee = employee,
                Address = repository.GetAddress().SingleOrDefault(x => x.AddressId == employee.AddressId)
            };
            return View(viewModel);
        }      
        
        //
        // GET: /Employee/Edit/5
        [Authorize]
        public ActionResult Edit(string id)
        {
            var viewModel = FillEmployeeViewModelForUpdate(id);
            return View(viewModel);
        }

        private EmployeeViewModel FillEmployeeViewModelForUpdate(string id)
        {
            var viewModel = new EmployeeViewModel
            {
                Employee = repository.GetEmployees().SingleOrDefault(x => x.UserId.ToString() == id),
                Titles = repository.GetTitles(),
                JobTitles = repository.GetJobTitles(),
                ContractTypes = repository.GetContractTypes()
            };
            return viewModel;
        }

        //
        // POST: /Employee/Edit/5

        [HttpPost]
        public ActionResult Edit(EmployeeViewModel model)
        {
            try
            {
                if (ModelState.IsValid)
                {
                    Employee employee = new Employee();
                    employee.UserId = model.Employee.UserId;
                    employee.TitleId = model.Employee.TitleId;
                    employee.FirstName = model.Employee.FirstName;
                    employee.LastName = model.Employee.LastName;
                    employee.StartDate = model.Employee.StartDate;
                    if (model.Employee.FinishDate.HasValue)
                        employee.FinishDate = model.Employee.FinishDate.Value;
                    employee.JobTitleId = model.Employee.JobTitleId;
                    employee.ContractTypeId = model.Employee.ContractTypeId;
                    employee.WorkPhone = model.Employee.WorkPhone;
                    employee.WorkEmail = model.Employee.WorkEmail;
                    employee.MobilePhone = model.Employee.MobilePhone;
                    employee.PrivateEmail = model.Employee.PrivateEmail;
                    employee.UpdatedBy = (Guid)Membership.GetUser(User.Identity.Name).ProviderUserKey;
                    employee.DateUpdated = DateTime.Now;

                    if (repository.UpdateEmployee(employee) > 0) {
                        return RedirectToAction("Details", new { id = model.Employee.UserId.ToString() });
                    }
                }
                else
                {
                    var viewModel = FillEmployeeViewModelForUpdate(model.Employee.UserId.ToString());
                    return View(viewModel);
                }
            }
            catch (Exception ex){
                DiagnosticLog.LogError(ex);
            }
            return View();
        }

        [Authorize]
        public ActionResult EditAddress(int id)
        {
            var viewModel = FillAddressModel(id);
            return View(viewModel);
        }

        private EmployeeViewModel FillAddressModel(int id)
        {
            var viewModel = new EmployeeViewModel()
            {
                Employee = repository.GetEmployees().SingleOrDefault(x => x.AddressId == id),
                Address = repository.GetAddress().SingleOrDefault(x => x.AddressId == id),
                Countries = repository.GetCountries()
            };
            return viewModel;
        }

        [HttpPost]
        [Authorize]
        public ActionResult EditAddress(EmployeeViewModel model)
        {
            try
            {
                Address address = new Address();
                address.AddressId = model.Address.AddressId;
                address.Address1 = model.Address.Address1;
                address.Address2 = model.Address.Address2;
                address.Town = model.Address.Town;
                address.PostalCode = model.Address.PostalCode;
                address.CountryId = model.Address.CountryId;

                if (repository.UpdateAddress(address) > 0)
                {
                    return RedirectToAction("Details", new { id = model.Employee.UserId.ToString() });
                }
            }
            catch (Exception ex) { DiagnosticLog.LogError(ex); }
            //If we get this far, that means something is wrong.
            var viewModel = FillAddressModel(model.Address.AddressId);
            return View(viewModel);
        }

        //
        // POST: /Employee/Delete/5     
        [HttpPost]
        [Authorize]
        public RedirectToRouteResult Delete(FormCollection form)
        {
           Employee employee = null;
            if (form.Count > 0)
            {
                string id = form["Employee.UserId"].ToString();
                employee = repository.GetEmployees().SingleOrDefault(x => x.UserId.ToString() == id);
                employee.IsDeleted = true;
                employee.UpdatedBy = (Guid)Membership.GetUser(User.Identity.Name).ProviderUserKey;
                employee.DateUpdated = DateTime.Now;
                if (repository.DeleteEmployee(employee) > 0) {
                    return RedirectToAction("List");
                }
            }
            return RedirectToAction("Details", new { id = employee.UserId.ToString() });
        }

        private void ModelStateError(string actionName)
        {
            try
            {
                StringBuilder sb = new StringBuilder();
                foreach (ModelState modelState in ViewData.ModelState.Values)
                {
                    foreach (ModelError error in modelState.Errors)
                    {
                        sb.AppendLine("Error Source: " + actionName);
                        sb.AppendLine("Exception: " + error.ErrorMessage);
                        sb.AppendLine("Exception: " + error.Exception + Environment.NewLine);
                    }
                }
                if (sb.Length > 0)
                {
                    DiagnosticLog.LogModelError(sb.ToString());
                }
            }
            catch (Exception ex)
            {
                DiagnosticLog.LogError(ex);
            }
        }                 
    }
}
